'use strict'

const fs = require('fs');
const router = require('koa-router')();
// 获取当前文件夹里的路由文件
function getRouterFile(ispath) {
    const thispath = ispath || __dirname;
    const file = fs.readdirSync(thispath);
    let getfile = file.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    })
    return getfile;
}
// l路由文件注册
function routerRegists(router, getfile) {
    console.log(getfile)
    getfile.forEach(item => {
        let getfilemodel = item.replace(".js", "");
        let routermodel = require(__dirname + "/" + getfilemodel);
        for (let id in routermodel) {
            let tmp = id.split(' ');
            let routerMethod = tmp[0];
            let routerUrl = tmp[1];
            let routerFunciton = routermodel[id];
            if (routerMethod === "get") {
                router.get(routerUrl, routerFunciton);
            } else if (routerMethod === "post") {
                router.post(routerUrl, routerFunciton);
            } else if (routerMethod === "put") {
                router.put(routerUrl, routerFunciton);
            } else if (routerMethod === "delete") {
                router.delete(routerUrl, routerFunciton);
            } else {

            }
        }

    });
    return router.routes();
}
// 暴露路由函数
module.exports = function(){
    let fn = getRouterFile();
    let fn1 = routerRegists(router,fn);
    return fn1;
}